package cn.tedu.bookshop.controller;

import cn.tedu.bookshop.mapper.UserMapper;
import cn.tedu.bookshop.pojo.dto.UserLoginDTO;
import cn.tedu.bookshop.pojo.dto.UserRegDTO;
import cn.tedu.bookshop.pojo.entity.User;
import cn.tedu.bookshop.pojo.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@RestController
public class UserController {
    @Autowired(required = false)
    UserMapper mapper;
    @RequestMapping("/reg")
    public int reg(@RequestBody UserRegDTO user){
        UserVO u = mapper.selectByName(user.getName());
        if (u!=null){
            return 1;
        }
        mapper.insert(user);
        return 2;
    }
    @RequestMapping("/login")
    public int login(@RequestBody UserVO user, HttpSession session,HttpServletResponse response) {
        UserVO u = mapper.selectByName(user.getName());
        if (u != null) {
            if (u.getPwd().equals(user.getPwd())) {
                session.setAttribute("user", u);
                return 0;
            }
            return 2;
        }
        return 1;
    }

    @RequestMapping("/getUserType")
    public User afterLogin(HttpSession session){
        return (User) session.getAttribute("user");
    }
}
